import cv2
import numpy as np

# 显示
def show_img(name,img):
    cv2.imshow(name, img)
    cv2.waitKey(0)
    cv2.destroyAllWindows()

# 银行卡号处理
img = cv2.imread("C:\\Users\\86191\\Pictures\\Saved Pictures\\Camera Roll\\cd.jpg")
# 放大
img = cv2.resize(img, (img.shape[1],img.shape[0]))
img_gary = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# 自适应阈值
# adaptiveThresh = cv2.adaptiveThreshold(img_gary, 255, cv2.ADAPTIVE_THRESH_MEAN_C,
#                                        cv2.THRESH_BINARY_INV, 13, 3)
# show_img("Gary", adaptiveThresh)
thresh = cv2.threshold(img_gary, 0, 255, cv2.THRESH_BINARY | cv2.THRESH_OTSU)[1]
# 轮廓查找，cv2.RETR_EXTERNAL(查找外轮廓)
show_img("Gary",thresh)
contours,hierarchy = cv2.findContours(thresh,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)
# 画出轮廓
cv2.drawContours(img,contours,-1,(0,0,255),3)

# 模板图片处理
tmp = cv2.imread("C:\\Users\\86191\\Pictures\\Saved Pictures\\Camera Roll\\tmp.jpg")
# 灰度化
tmp_gary = cv2.cvtColor(tmp, cv2.COLOR_BGR2GRAY)
# 二值化
ret,thresh_tmp = cv2.threshold(tmp_gary, 127, 255, cv2.THRESH_BINARY_INV)
# 轮廓查找，cv2.RETR_EXTERNAL(查找外轮廓)
contours,hierarchy = cv2.findContours(thresh_tmp,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)
cv2.drawContours(tmp,contours,-1,(0,0,255),3)
# show_img("tmp",thresh_tmp)
# show_img("tmp_gary",tmp)

# 轮廓排序与截取
def get_contour(img,width,height):
    contours,hierarchy = cv2.findContours(img,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)
    # 轮廓排序
    rect1 = np.ones((len(contours),4),dtype=int)
    for i in range(len(contours)):
        # 存储轮廓
        rect1[i] = cv2.boundingRect(contours[i])
    rect2 = np.ones((len(contours),4),dtype=int)
    for i in range(len(contours)):
        s = 0
        for j in range(len(contours)):
           if rect1[i][0] > rect1[j][0]:
               s += 1
        rect2[s] = rect1[i]

    # 截取
    img_rect = [[] for i in range(len(contours))]
    for i in range(len(contours)):
        x,y,w,h = rect2[i]
        roi = img[y:y+h,x:x+w]
        roi = cv2.resize(roi,(width,height))
        ret,thresh = cv2.threshold(roi,127,255,cv2.THRESH_BINARY_INV)
        # show_img("roi",roi)
        # show_img("thresh",thresh)
        img_rect[i] = thresh
    return rect2,img_rect

rect2_tmp,img_rect_tmp = get_contour(thresh_tmp,100,160)
rect2,img_rect = get_contour(thresh ,100,160)
show_img('img',img_rect[0])
# print(rect2_tmp)
# print(rect2)
result = []
for i in range(len(img_rect)):
    score = np.zeros(len(img_rect_tmp),dtype=int)
    for j in range(len(img_rect_tmp)):
        score[j] = cv2.matchTemplate(img_rect[i], img_rect_tmp[j], cv2.TM_SQDIFF)
    min_val, max_val, min_indx, max_indx = cv2.minMaxLoc(score)
    result.append(min_indx[1])
print(result)







